﻿using Application.Features.Auth.Commands;
using Application.Features.Auth.DTOs;
using Application.Features.Menus.DTOs;
using Application.Features.Menus.Queries.GetUserMenuByUserId;
using Common.Models;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Mvc;
using System.ComponentModel;

namespace WebAPI.Controllers;

/// <summary>
/// 授权管理
/// </summary>
[Description("授权管理")]
[AllowAnonymous]
public class AuthController : ApiControllerBase
{
    /// <summary>
    /// 密码登录
    /// </summary>
    /// <returns></returns>
    [HttpPost("login")]
    [Description("密码登录")]
    public async Task<Result<LoginOutput>> LoginByPasswordAsync(LoginByPasswordCommand command)
    {
        return await Result<LoginOutput>.SucceedAsync(await Mediator.Send(command));
    }

    /// <summary>
    /// 刷新令牌
    /// </summary>
    /// <returns></returns>
    [HttpPost("refresh-token")]
    [Description("刷新令牌")]
    public async Task<Result<RefreshTokenOutput>> RefreshTokenAsync(RefreshTokenCommand command)
    {
        return await Result<RefreshTokenOutput>.SucceedAsync(await Mediator.Send(command));
    }

    /// <summary>
    /// 注册用户
    /// </summary>
    /// <returns></returns>
    [HttpPost("register")]
    [Description("注册用户")]
    public async Task<Result> RegisterAsync(RegisterCommand command)
    {
        await Mediator.Send(command);
        return await Result.SucceedAsync();
    }

    /// <summary>
    /// 动态路由
    /// </summary>
    /// <returns></returns>
    [HttpGet("get-async-routes")]
    [Description("动态路由")]
    public Task<string> RoutesAsync()
    {
        var routesFilePath = Path.Combine(Directory.GetCurrentDirectory(), "routes.json");

        if (!System.IO.File.Exists(routesFilePath))
        {
            throw new FileNotFoundException("routes.json 文件未找到。");
        }

        var json = System.IO.File.ReadAllText(routesFilePath);       
        return Task.FromResult(json);
    }

    /// <summary>
    /// 查询用户的菜单
    /// </summary>
    /// <returns></returns>
    [HttpGet("user/menus")]
    [Description("查询用户的菜单")]
    public async Task<Result<IEnumerable<UserMenuTreeOutput>>> GetMenusByUserIdQueryAsync()
    {
        var data = await Mediator.Send(new GetMenusByUserIdQuery());
        return await Result<IEnumerable<UserMenuTreeOutput>>.SucceedAsync(data);
    }
}
